package com.glory.dgcpcpda.activity.mfg;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.DefectListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.entity.DefectCodeEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.LotList;
import com.glory.dgcpcpda.entity.PackageEntity;
import com.glory.dgcpcpda.entity.ScrapEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PackageDownTubeActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvCircuitName)
    TextView tvCircuitName;
    @BindView(R.id.tvCustomCode)
    TextView tvCustomCode;
    @BindView(R.id.tvPackageFrom)
    TextView tvPackageFrom;
    @BindView(R.id.tvStates)
    TextView tvStates;
    @BindView(R.id.tvGoodsNum)
    TextView tvGoodsNum;
    @BindView(R.id.etTrackOutNum)
    EditText etTrackOutNum;
    @BindView(R.id.rvSpiltLotList)
    RecyclerView rvSpiltLotList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvPackageCode)
    LinearLayout tvPackageCode;
    @BindView(R.id.etPackageCode)
    EditText etPackageCode;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvLotQTY)
    TextView tvLotQTY;
    @BindView(R.id.tvPackageQTY)
    TextView tvPackageQTY;
    @BindView(R.id.cbReel)
    CheckBox cbReel;
    @BindView(R.id.tvTubePackageTitle)
    TextView tvTubePackageTitle;
    @BindView(R.id.tvTubeTrackOutTitle)
    TextView tvTubeTrackOutTitle;
    @BindView(R.id.cbSample)
    CheckBox cbSample;
    @BindView(R.id.tvGrade)
    TextView tvGrade;
    @BindView(R.id.tvTips)
    TextView tvTips;
    @BindView(R.id.flDefectList)
    FrameLayout flDefectList;
    @BindView(R.id.ivDefectArrow)
    ImageView ivDefectArrow;
    @BindView(R.id.tvDefectCode)
    TextView tvDefectCode;
    @BindView(R.id.rvDefectList)
    RecyclerView rvDefectList;
    @BindView(R.id.tvDefectNum)
    TextView tvDefectNum;
    @BindView(R.id.defectLayout)
    LinearLayout defectLayout;

    private int mMaxReelQTY;
    private int mPackageQTY;
    private boolean iszkd = false;
    private String zkd = "";
    private List<String> defectCodeList;
    private FreeUI_GeneralPop codePop;
    private DefectListAdapter defectListAdapter;
    private LotInfoEntity lotInfoEntity;
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_package_down;
    }

    @Override
    protected void initView() {
        tvTitle.setText("包装管装下架");
        setMainLayout(llMain);
        tvTubePackageTitle.setText("货架盒数");
        tvTubeTrackOutTitle.setText("出站盒数");
        cbReel.setText("尾数盒先出");

        defectCodeList = new ArrayList<>();
        initRecyclerView(rvDefectList, this);
        defectListAdapter = new DefectListAdapter(null, tvDefectNum);
        defectListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        defectListAdapter.isFirstOnly(true);
        rvDefectList.setAdapter(defectListAdapter);

        initEdit(etLot, s -> LotUtils.searchLotInfo(PackageDownTubeActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
            @Override
            public void onSuccess(LotInfoEntity response) {
                defectListAdapter = new DefectListAdapter(null, tvDefectNum);
                defectListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
                defectListAdapter.isFirstOnly(true);
                rvDefectList.setAdapter(defectListAdapter);

                lotInfoEntity = response;
                tvCircuitName.setText(response.getPRODUCTMODEL());
                tvCustomCode.setText(response.getLOT().getCUSTOMERCODE());
                tvPackageFrom.setText(response.getLOT().getMAINMATTYPE());
                tvStates.setText(response.getLOT().getSTATE());
                tvLotQTY.setText(response.getLOT().getMAINQTY());
                defectListAdapter.setTotalNum(Double.parseDouble(response.getLOT().getMAINQTY()));
                if(!response.getZKD().contains("PASS")&&!response.getZKD().equals("")&&!response.getZKD().equals(null)){
                    if(response.getZKD().contains("EMPTY")){
                        showConfirmDialog(response.getZKD());
                    }else {
                        zkd=response.getZKD();
                        iszkd = true;
                        tvPackageCode.setVisibility(View.VISIBLE);
                        etPackageCode.setFocusable(true);
                        etPackageCode.requestFocus();
                    }
                }
                else {
                    iszkd = false;
                    tvPackageCode.setVisibility(View.GONE);
                }
                if("T3000".equals(response.getLOT().getSTEPNAME())){
                    defectLayout.setVisibility(View.VISIBLE);
                    getDefectInfo(s);
                }else{
                    defectLayout.setVisibility(View.GONE);
                }
                requestData(s);

            }
            @Override
            public void onFail(Throwable t) {
                loadError(t, "LOTQUERY");
            }
        }));

        initEdit(etPackageCode, s -> {
            if(!s.equals(zkd)){
                showConfirmDialog("真空包装编码"+s+"不匹配，请检查");
                new Handler().postDelayed(() -> etPackageCode.requestFocus(), 500);
                return;
            }
            iszkd=false;
        });

    }

    private void requestData(String s) {
        FreeUI_EntityCallBack<BaseResponseBean<PackageEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<PackageEntity>>
                (new TypeToken<BaseResponseBean<PackageEntity>>() {
                }.getType(), getSupportFragmentManager(), PackageDownTubeActivity.this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<PackageEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    mMaxReelQTY = response.body().getResponse().getBody().getMAXREELQTY();
                    etTrackOutNum.setText(String.valueOf(mMaxReelQTY));
                    mPackageQTY = response.body().getResponse().getBody().getPACKAGEQTY();
                    tvPackageQTY.setText(String.valueOf(mPackageQTY));
                    tvGrade.setText(response.body().getResponse().getBody().getBINGRADE());
                    tvTips.setText(response.body().getResponse().getBody().getWARNINGINFO());
                    String sampleinfo = response.body().getResponse().getBody().getSAMPLEINFO();
                    String warmingInfo=response.body().getResponse().getBody().getWARNINGINFO();
                    if(warmingInfo!=null&&!warmingInfo.equals("")){
                        showConfirmDialog(warmingInfo);
                    }
                    if (!sampleinfo.equals("")){
                        showConfirmDialog(sampleinfo);
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<PackageEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PACKAGEUPSHELFTUBE");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "UNBINDSELECT");
        map.addProperty("LOTID", s);
        NetUtils.requestPostNet("CPC.PACKAGEUPSHELFTUBE", "PACKAGEUPSHELFTUBE", PackageDownTubeActivity.this, map, callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit,R.id.flDefectList, R.id.cbReel})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tvBaseSubmit) {
            try {
                if (getText(etLot).equals("") || getText(etTrackOutNum).equals("")) {
                    showToast("批次号或出站盒数不能为空", false);
                    return;
                }
                if(iszkd){
                    showToast("真空包装袋未校验，不允许下架", false);
                    return;
                }

                if (Integer.parseInt(getText(etTrackOutNum)) != mMaxReelQTY) {
                    if (Integer.parseInt(getText(etTrackOutNum)) > mPackageQTY) {
                        showToast("出站盒数不能大于总盒数", false);
                        return;
                    }
                    FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "与系统推荐的盒数不符，剩余数量：" + (mPackageQTY - Integer.parseInt(getText(etTrackOutNum))) + "盒。是否确认下架?",
                            () -> packageDown(), () -> {

                            }).show(getSupportFragmentManager(), "SUBMIT_DIALOG");
                } else {
                    FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "剩余数量:" + (mPackageQTY - Integer.parseInt(getText(etTrackOutNum))) + "盒。是否确认下架？",
                            () -> packageDown(), () -> {

                            }).show(getSupportFragmentManager(), "SUBMIT_DIALOG");
                }
            } catch (NumberFormatException e) {
                showToast("请输入数字", false);
            }
            //clear();
        }else if (view.getId() == R.id.flDefectList){
            if (defectCodeList.size() <= 0) {
                showToast("未获取到不良代码列表", false);
                return;
            }

            if (codePop != null) {
                if (codePop.isShowing()) {
                    codePop.dismiss();
                }
            } else {
                codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flDefectList.getWidth(), defectCodeList, ivDefectArrow, (codeS, i) -> {
                    tvDefectCode.setText(codeS.split("/")[0]);
                    ScrapEntity scrapEntity = new ScrapEntity();
                    scrapEntity.setACTIONCODE(codeS.split("/")[0]);
                    scrapEntity.setACTIONREASON(codeS.split("/")[1]);
                    scrapEntity.setLOTID(lotInfoEntity.getLOT().getLOTID());
                    scrapEntity.setLOTRRN(lotInfoEntity.getLOT().getOBJECTRRN());
                    scrapEntity.setACTIONTYPE("Scrap");

                    if (defectListAdapter.getData().size() > 0) {
                        if (containCode(scrapEntity)) {
                            defectListAdapter.addData(scrapEntity);
                        }
                    } else {
                        defectListAdapter.addData(scrapEntity);
                    }

                });
            }
            FreeApi_PopUtils.setArrowShow(ivDefectArrow);
            codePop.showAsDropDown(flDefectList, 0, 0);
        }
    }

    private void clear() {
        etLot.setText("");
        tvCircuitName.setText("");
        tvCustomCode.setText("");
        tvPackageFrom.setText("");
        tvStates.setText("");
        tvLotQTY.setText("");
        etTrackOutNum.setText("");
        etLot.requestFocus();
        rvDefectList.setAdapter(new DefectListAdapter(null, tvDefectNum));
        tvDefectCode.setText("");
        defectCodeList.clear();
    }

    private void packageDown() {
        FreeUI_EntityCallBack<BaseResponseBean<PackageEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<PackageEntity>>
                (new TypeToken<BaseResponseBean<PackageEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<PackageEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    PackageEntity body = response.body().getResponse().getBody();
                    showConfirmDialog(body.getSAMPLEINFO().equals("") ? "下架成功" : body.getSAMPLEINFO());
                    tvPackageCode.setVisibility(View.GONE);
                    clear();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<PackageEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PACKAGEUPSHELFTUBE");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "UNBIND");
        map.addProperty("LOTID", getText(etLot));
        map.addProperty("CONSUMEQTY", getText(etTrackOutNum));
        map.add("LOTACTIONLIST",new JsonParser().parse(new Gson().toJson(defectListAdapter.getData())).getAsJsonArray());
        map.addProperty("ISENDFLAG", cbReel.isChecked() ? "Y" : "N");
//        map.addProperty("ISSAMPLE", cbSample.isChecked() ? "Y" : "N");
        NetUtils.requestPostNet("CPC.PACKAGEUPSHELFTUBE", "PACKAGEUPSHELFTUBE", this, map, callBack);
    }
    private void getDefectInfo(String s) {

        FreeUI_EntityCallBack<BaseResponseBean<DefectCodeEntity>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<DefectCodeEntity>>
                (new TypeToken<BaseResponseBean<DefectCodeEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    defectCodeList.clear();
                    List<DefectCodeEntity.DefectCode> scrapcodelists = response.body().getResponse().getBody().getSCRAPCODELISTS();
                    for (DefectCodeEntity.DefectCode code : scrapcodelists){
                        defectCodeList.add(code.getKEYID() + "/" + code.getDESCRIPTION());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"GETSTEPBYLOT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "BYLOT");
        map.add("LOT", new JsonParser().parse(new Gson().toJson(new LotList(s))).getAsJsonObject());//传批次集合
        NetUtils.requestPostNet("MES.GETSTEPBYLOT", "GETSTEPBYLOT", this, map, callback);
    }
    private boolean containCode(ScrapEntity scrapEntity) {
        for (ScrapEntity bean : defectListAdapter.getData()) {
            if (bean.getACTIONCODE().equals(scrapEntity.getACTIONCODE())) {
                showToast("列表中已有当前不良代码!", false);
                return false;
            }
        }
        return true;
    }
}
